package cn.jbit.generatedbdata.generateData;

import cn.jbit.generatedbdata.GenerateAllData;
import cn.jbit.generatedbdata.config.ConfigurationManager;
import cn.jbit.generatedbdata.constant.Constants;
import cn.jbit.generatedbdata.tools.StringUtil;
import com.alibaba.fastjson.JSONObject;;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;

/**
 *  将数据准备成json格式数据，发送到数据采集接口中
 * @author 张在成
 */
public class GenerateUserLoginLocationData extends Thread{

    @Override
    public void run() {
        GenerateData();
    }

    private void GenerateData() {
        //所有请求事件类型为userlog，不再区分
        String logType = "userlog";
        String url="http://DataWareHouse:8686/collector/commonLog/"+logType;
//        String url="http://localhost:8686/collector/common/"+logType;
        //调用接口返回结果
        String result = null;
        HttpClient client = HttpClients.createDefault();
        HttpPost post = new HttpPost(url);
        //设置请求头
        post.setHeader("Content-Type", "application/json");

        //循环获取对应的日志数据，生产到对应的数据采集接口中
        while(true){
            InputStream in = null;
            BufferedReader br = null;
            try{
                /**
                 * 获取日志文件数据路径:
                 * GenerateUserLogData.class.getClassLoader().getResource().getPath 获取的是编译后classes文件夹的根路径
                 */
                in= GenerateAllData.class.getClassLoader().getResourceAsStream("user_login_location_info.txt");
                br=new BufferedReader(new InputStreamReader(in));
                String line=br.readLine();
                while (line!=null){
                    //解析读取到的每行数据，组织成json
                    //'170001'^'27690816'^'28.2002'^'113.0054'^'20200105104952'^'89615'
                    String[] split = line.split("\\^");
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("uid", StringUtil.strTrimStartAndEnd(split[1]));
                    jsonObject.put("lat",StringUtil.strTrimStartAndEnd(split[2]));
                    jsonObject.put("lng",StringUtil.strTrimStartAndEnd(split[3]));
                    jsonObject.put("mid",StringUtil.strTrimStartAndEnd(split[5]));
                    //设置当前json日志标记 event_type 为 user_login_location_log
                    jsonObject.put("event_type","USER_LOGIN_LOCATION_LOG");

                    //设置用户登录日期
                    long currentTimeMillis = System.currentTimeMillis();
                    jsonObject.put("login_dt", currentTimeMillis);

                    //设置请求体
                    post.setEntity(new StringEntity("["+jsonObject.toString()+"]",Charset.forName("UTF-8")));
                    //设置用户日志每隔多长时间发送一条数据
                    Thread.sleep(Long.valueOf(ConfigurationManager.getProperty(Constants.USERLOG_SEND_INTERVAL)));

                    //获取返回信息
                    HttpResponse response = client.execute(post);
                    if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
                        result = EntityUtils.toString(response.getEntity(), "utf-8");
                    }
                    System.out.println("SpringBoot服务端返回结果："+result);
                    //将每条数据发送到对应的日志采集接口中，获取下一条数据
                    line=br.readLine();
                }
            }catch (Exception e){
                e.printStackTrace();
            }finally {
                try {
                    br.close();
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
